import socket
import sys
import threading
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*
from PyQt5.QtGui import*
from ui.Ui_mainwindow import Ui_MainWindow
from common.utils import decode_dat
from drivers.driver_net import net_Driver
class MainWindow(QMainWindow):

    def __init__(self) -> None:
        super().__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.net_driver = net_Driver()

        # 连接信号与槽函数
        self.net_driver.on_rev_signal.connect(self.on_rev_slot)
        self.ui_init()
    # 定义槽函数 int 如果为0表示更新按钮状态,1表示在rev框接受数据
    @pyqtSlot(int,str)
    def on_rev_slot(self,type_t,msg):
        thread_name = threading.current_thread().name
        print("thread_name:{},msg={}".format(thread_name,msg))
        if type_t ==1:
            self.ui.edit_rev.appendPlainText(msg)
        else:
            self.update_connect_state()

    def update_connect_state(self):
        if not self.net_driver.tcp_is_connected():
            # 断开连接
            self.ui.btn_connect.setText("连接网络")
            self.ui.btn_connect.setIcon(QIcon(":/icon/disconnect"))
        else:
            # 连接网络
            self.ui.btn_connect.setText("断开连接")
            self.ui.btn_connect.setIcon(QIcon(":/icon/connect"))

    """
    on_组件名_如clicked会传递checkable如果不设置@pyqtSlot既调用无参click
    又调用传递参数的checkable
    """
    @pyqtSlot()
    def on_btn_connect_clicked(self):
        """
        1.获取用户输入的ip及端口
        2.创建子线程（可能连接服务器较慢）
        3.创建socket对象并连接服务器
        4.正常收发数据
        """
        # 当tcp_client对象不为空时按钮按下表示断开连接
        if self.net_driver.tcp_is_connected():
            #self.on_rev_signal.emit(0, "None")
            # self.update_connect_state()
            self.net_driver.tcp_disconnected()
            return

        mode =  self.ui.cb_mode.currentText()
        target_ip = self.ui.edit_target_ip.text()
        target_port = self.ui.edit_target_port.text()
        # print(target_ip, target_port)
        self.net_driver.connect_server(target_ip, target_port)

    @pyqtSlot() 
    def on_btn_send_clicked(self):
        # 获取发送框的消息
        text = self.ui.edit_send.toPlainText()
        if len(text)==0:
            # self.statusBar().showMessage("请输入内容再发送",1000)
            print("请输入内容再发送")
            return
        if not self.net_driver.tcp_is_connected():
            QMessageBox.warning(self,"发送失败","请连接后再发送")
            print("请连接服务器再发送")
            return
        self.net_driver.send_msg(text)

    def ui_init(self):
        # self.ui.btn_connect.clicked.connect(self.on_btn_connect_clicked)
        self.ui.edit_target_ip.setText("127.0.0.1")
        self.ui.edit_target_port.setText("8888")
        

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    window = MainWindow()
    
    window.show()
    
    sys.exit(app.exec_())
